import React,{ useState, useEffect } from 'react';
import { Line } from '@ant-design/charts';
import { DatePicker } from 'antd';
import dayjs from 'dayjs';

const fommatData=(list)=>{
  const map = new Map()
  list.forEach(item=>{
    if(map.has(item.time)){
      let price = map.get(item.time)
      let price2 = price + Number(item.price)
      map.set(item.time,Number(price2.toFixed(2)))
    }else{
      map.set(item.time,Number(item.price))
    }
  })
  const objList = Array.from(map, ([label, value]) => {
    return { label: label.slice(-2), value }
  });
  return objList
}
const LineCharts = (props) => {
    const defaultValue = dayjs().format('YYYY-MM'); // 当前时间
    const {list} = props;
    const [selectedMonth, setSelectedMonth] = useState(defaultValue); // 选择的月份
    const [chartData, setChartData] = useState([]); // 图表数据
    useEffect(()=>{
      console.log("lineuseEffect")
      let timeData = list.filter(item=>item.time.slice(0,7) === selectedMonth)
      setChartData(fommatData(timeData))
    },[selectedMonth,list])
    const config = {
        data:chartData,
        xField: 'label',
        yField: 'value',
    };
    const onChange = (date, dateString) => {
      setSelectedMonth(dateString);
    };
  return (
    <div className="charts-box">
        <div className='charts-header'>月份<DatePicker onChange={onChange} picker="month" defaultValue={dayjs(defaultValue, 'YYYY-MM')} /></div>
        <div className='charts-item'>
            <Line {...config } />
        </div>
     </div> 
  )
}
export default LineCharts